package com.cl.code.database.mbp.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cl.code.common.constant.FixedFieldConstant;
import com.cl.code.common.utils.CurrentUserUtils;
import com.cl.code.common.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MybatisPlusFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.trace("开始插入填充...");
        Long currentUserId = getCurrentUserId();
        this.strictInsertFill(metaObject, FixedFieldConstant.CREATE_USER_ID, Long.class, currentUserId);
        this.strictInsertFill(metaObject, FixedFieldConstant.CREATE_TIME, Long.class, TimeUtils.now());
        this.strictInsertFill(metaObject, FixedFieldConstant.VERSION, Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.trace("开始更新填充...");
        Long currentUserId = getCurrentUserId();
        this.strictInsertFill(metaObject, FixedFieldConstant.UPDATE_USER_ID, Long.class, currentUserId);
        this.strictUpdateFill(metaObject, FixedFieldConstant.UPDATE_TIME, Long.class, TimeUtils.now());
    }

    private Long getCurrentUserId() {
        return CurrentUserUtils.getCurrentUserId();
    }

}